JlojaTags = {
	name: 'tag[]',
	
	addTagFromInput: function( input )
	{
		input.value = $( input ).value.trim();
		input.disabled = 'disabled';
		this.addTagToFormFromInput( input );
		input.value = '';
		input.disabled = '';
	},
	
	addTag: function( tagElement )
	{
		var tag = jQuery(tagElement )[0];
		if( tag.className.search( 'pressed' ) > 0 ){
			tag.removeClass( 'pressed' );
		}
		else{
			tag.addClass( 'pressed' );
		}

		this.getSelectedTags();
	},

	getSelectedTags: function()
	{
		var that = this;
		this.clearForm();
		jQuery( '#param-tags-availables .pressed' ).each( function( el ) {
			that.addTagToForm( this.innerHTML );
		});
	},

	clearForm: function()
	{
		$( 'param-tags-div-tags' ).innerHTML = '';
	},
	
	addTagToForm: function( tag )
	{
		jQuery( '#param-tags-div-tags' ).append(
			jQuery( '<input type="text" name="' + this.name + '" value="' + tag + '" onclick="JlojaTags.remove( this );"/>' )
		);

	},

	addTagToFormFromInput: function( tag )
	{
		var that = this;
		var have = false;

		jQuery( '#param-tags-availables' ).children().each( function( i ) {
			if( this.innerHTML.trim() == tag.value && this.className.search( 'pressed' ) < 0 ){
				that.addTag( this );
				have = true;
			}
		});

		//search if the tag aready has ben added
		jQuery( '#param-tags-div-tagsinput' ).children().each( function( i ){
			if( this.value.trim() == tag.value ){
				have = true;
			}
		});

		if( have ){
			return;
		}
		
		jQuery( '#param-tags-div-tagsinput' ).append(
			jQuery( '<input type="text" name="' + this.name + '" value="' + tag.value + '" onclick="JlojaTags.remove( this );"/>' )
		);
	},

	remove: function( input )
	{
		var that = this;
		var have = false;
		jQuery( '#param-tags-availables .pressed' ).each( function( i ) {
			if( this.innerHTML.trim() == input.value ){
				that.addTag( this );
				have = true;
			}
		});

		if( !have ){
			jQuery( input ).remove();
		}
	}
}